package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.bouncycastle.jcajce.provider.asymmetric.X509;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @author: wxw
 * @ClassName: listener
 * @JdkVersion: JDK1.8
 * @Version: 1.0.0
 * @Since: 2025/2/24 19:50
 * @Description: 文章上下架状态更新的MQ监听器
 */
@Component
@Slf4j
public class ArticleDownOrUpListener {

    @Autowired
    private ApArticleConfigService apArticleConfigService;


    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void msg(ConsumerRecord<String, String> consumerRecord) {
        Optional<ConsumerRecord<String, String>> optional = Optional.ofNullable(consumerRecord);
        optional.ifPresent(x -> {
            log.info("[APP文章上下架状态更新]开始更新。。。。。。。。。。");
            Map map = JSON.parseObject(x.value(), Map.class);
            Long articleId = Long.valueOf(String.valueOf(map.get("articleId")));
            Integer enable = Integer.valueOf(String.valueOf(map.get("enable")));
            Boolean isDown = true; // 默认已下架 true - 1
            if (enable == 1) {
                isDown = false; // 未下架（已上架） - 0
            }
            // 更新APP文章的上下架状态 update ap_article_config set is_down = ? where article_id =
            boolean result = apArticleConfigService.update(Wrappers.<ApArticleConfig>lambdaUpdate()
                    .eq(ApArticleConfig::getArticleId, articleId)
                    .set(ApArticleConfig::getIsDown, isDown)
            );
            log.info("[APP文章上下架状态更新]更新结束，更新结果：{}",result);
        });

    }


}
